package top.lbqaq.filter;

import top.lbqaq.pojo.User;
import top.lbqaq.util.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author luoboQAQ
 * @Date 2021/12/4
 */
public class PermissionFilter implements Filter {

    private static final String SUPER_ADMIN = "超级管理员";
    private static final String ADMIN = "管理员";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        String path = req.getRequestURI() + "?" + req.getQueryString();
        String role = user.getRoleName();
        if (SUPER_ADMIN.equals(role)) {
            filterChain.doFilter(req, resp);
            return;
        }
        for (int i = 0; i < Constants.NEED_PERMISSION_ADMIN.length; i++) {
            if (path.toLowerCase().contains(Constants.NEED_PERMISSION_ADMIN[i])) {
                if (ADMIN.equals(role)) {
                    filterChain.doFilter(req, resp);
                } else {
                    req.setAttribute("error", "您没有权限访问");
                    req.getRequestDispatcher("/error.jsp").forward(req, resp);
                }
                return;
            }
        }
        filterChain.doFilter(req, resp);
    }

    @Override
    public void destroy() {

    }
}
